//
//  DMIronsourceManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/7/9.
//

#import "DMIronsourceManager.h"
#import "../../Utils/Logger/IMLogUtils.h"

#import <FirebaseAnalytics/FirebaseAnalytics.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <AdjustSdk/AdjustSdk.h>

#import "DMBannerManager.h"
#import "DMInterstitialManager.h"
#import "DMRewardedVideoManager.h"
#import "DMNativeAdManager.h"
#import "DMConfigReader.h"
#import "DMCommercialManager.h"

static DMIronsourceManager *_ironSource = nil;

@interface DMIronsourceManager()<LPMImpressionDataDelegate>


@end

@implementation DMIronsourceManager

+ (instancetype)shareIronSourceManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _ironSource = [[self alloc] init];
        
    });
    return _ironSource;
}

- (void)initIronSource
{
#if IRONSOURCE_AVAILABLE
#ifdef DEBUG
//     This is used to validate the integration.
//     Remove it before going live!
    [LevelPlay validateIntegration];
    [LevelPlay setMetaDataWithKey:@"is_test_suite" value:@"enable"];
#endif
//     Create a request builder with app key and ad formats. Add User ID if available.
    
    [LevelPlay addImpressionDataDelegate:self];
    
    LPMInitRequestBuilder *requestBuilder = [[LPMInitRequestBuilder alloc] initWithAppKey:[[DMConfigReader sharedInstance]ironSourceAppKey]];
    [requestBuilder withLegacyAdFormats:@[IS_REWARDED_VIDEO,IS_INTERSTITIAL,IS_BANNER,IS_NATIVE_AD]];

//     Build the initial request
    LPMInitRequest *initRequest = [requestBuilder build];
//     Initialize LevelPlay with the prepared request
    [LevelPlay initWithRequest:initRequest completion:^(LPMConfiguration *_Nullable config, NSError *_Nullable error){
        if(error) {
//             There was an error on initialization. Take necessary actions or retry.
            [IMLogUtils error:IMLogTagSDKInit format:@"IronSource initialization failed: %@", error.localizedDescription];
        } else {
//            Initialization was successful. You can now create ad objects and load ads.
            [IMLogUtils info:IMLogTagSDKInit format:@"IronSource initialization successful"];
            
            [[DMBannerManager shareBannerManager]setBannerDelegate];
            [[DMInterstitialManager shareInterstitialManager]interstitialDelegate];
            [[DMRewardedVideoManager shareRewardedVideoManager]irDelegate];
            [[DMNativeAdManager sharedInstance]initWithNativead];
        }
    }];
#else
    [IMLogUtils info:IMLogTagSDKInit format:@"IronSource framework not available, initialization skipped"];
#endif
}

- (void)impressionDataDidSucceed:(LPMImpressionData *)impressionData {
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] 💸 ========== 收到 Impression Data =========="];
    
    if (!impressionData || !impressionData.revenue) {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [Rewarded] ❌ Impression data 无效或收入为空"];
        return;
    }

    double revenueUSD = impressionData.revenue.doubleValue;
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] 💰 Impression 收入详情:"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - InstanceName: %@", impressionData.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - AdNetwork: %@", impressionData.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - AdUnitId: %@", impressionData.mediationAdUnitId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - Revenue: $%.6f", revenueUSD];
    
    NSString *AdUnitId = impressionData.mediationAdUnitId;
    NSString *ad_format = @"unknown";
    NSString *adSource = @"unknown"; // 主广告位还是备用广告位
    
    // 判断广告类型和广告源（主/备用广告位）
    if ([AdUnitId isEqualToString:[DMConfigReader primaryRewardForSDKConfigFile]]) {
        ad_format = @"rewarded_video";
        adSource = [AdUnitId isEqualToString:[DMConfigReader primaryRewardForSDKConfigFile]] ? @"primary" : @"main";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"RV_RevenueUSD"];
    } else if ([AdUnitId isEqualToString:[DMConfigReader secondaryRewardForSDKConfigFile]]) {
        ad_format = @"rewarded_video";
        adSource = @"secondary";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"RV_RevenueUSD"];
    } else if ([AdUnitId isEqualToString:[DMConfigReader primaryInterForSDKConfigFile]]) {
        ad_format = @"interstitial";
        adSource = [AdUnitId isEqualToString:[DMConfigReader primaryInterForSDKConfigFile]] ? @"primary" : @"main";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Inter_RevenueUSD"];

    } else if ([AdUnitId isEqualToString:[DMConfigReader secondaryInterForSDKConfigFile]]) {
        ad_format = @"interstitial";
        adSource = @"secondary";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Inter_RevenueUSD"];

    } else if ([AdUnitId isEqualToString:[DMConfigReader primaryBannerForSDKConfigFile]]) {
        ad_format = @"banner";
        adSource = [AdUnitId isEqualToString:[DMConfigReader primaryBannerForSDKConfigFile]] ? @"primary" : @"main";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Banner_RevenueUSD"];

    } else if ([AdUnitId isEqualToString:[DMConfigReader secondaryBannerForSDKConfigFile]]) {
        ad_format = @"banner";
        adSource = @"secondary";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Banner_RevenueUSD"];

    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - ad_format: %@", ad_format];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - ad_source: %@", adSource];
    
    // ========== DMCommercialManager 策略集成 ==========
    DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
    
    // 1. 记录广告位性能数据
    [commercialSDK recordAdUnitPerformance:AdUnitId
                                      ecpm:revenueUSD
                                 fillRate:1.0
                                 clickRate:0.0
                                 isSuccess:YES];
    
    // 2. 应用FB策略控制（如果是激励视频）
    if ([ad_format isEqualToString:@"rewarded_video"]) {
        BOOL shouldSwitchAd = [commercialSDK shouldSwitchAdForType:@"rewarded_video"
                                                        adUnitId:AdUnitId];
        if (shouldSwitchAd) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] 🔄 FB策略触发：建议切换广告位"];
            // 通知RewardedVideoManager切换广告位
            [[DMRewardedVideoManager shareRewardedVideoManager] switchToSecondaryAdIfNeeded];
        }
    }
    
    // 3. ECPM比较和广告位优化（双广告位模式）
    if ([adSource isEqualToString:@"primary"] || [adSource isEqualToString:@"secondary"]) {
        NSString *primaryAdUnitId = nil;
        NSString *secondaryAdUnitId = nil;
        
        if ([ad_format isEqualToString:@"rewarded_video"]) {
            primaryAdUnitId = [DMConfigReader primaryRewardForSDKConfigFile];
            secondaryAdUnitId = [DMConfigReader secondaryRewardForSDKConfigFile];
        } else if ([ad_format isEqualToString:@"interstitial"]) {
            primaryAdUnitId = [DMConfigReader primaryInterForSDKConfigFile];
            secondaryAdUnitId = [DMConfigReader secondaryInterForSDKConfigFile];
        } else if ([ad_format isEqualToString:@"banner"]) {
            primaryAdUnitId = [DMConfigReader primaryBannerForSDKConfigFile];
            secondaryAdUnitId = [DMConfigReader secondaryBannerForSDKConfigFile];
        }
        
        if (primaryAdUnitId && secondaryAdUnitId) {
            NSString *optimalAdUnitId = [commercialSDK compareAdUnitsAndSelectOptimal:primaryAdUnitId
                                                                      secondaryAdUnitId:secondaryAdUnitId];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] 🎯 ECPM比较结果：最优广告位 = %@", optimalAdUnitId];
        }
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData]   - ad_format: %@", ad_format];
    // ========== 原有上报逻辑保持不变 ==========
    // 1. 上报 Taichi
    NSNumber *revenueMicros = @(revenueUSD * 1000);
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] Taichi 上报完成: %@ micros", revenueMicros];

    // 2. Firebase 埋点
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"ad_platform"] = @"ironSource";
    params[@"ad_unit"] = impressionData.mediationAdUnitId ?: @"";
    params[@"ad_format"] = ad_format;
    params[@"ad_source"] = impressionData.adNetwork ?: @"";
    params[@"ad_unit_name"] = impressionData.instanceName ?: @"";
    params[@"ad_unit_source"] = adSource; // 新增：标识主/备用广告位
    params[@"value"] = @(revenueUSD);
    params[@"currency"] = @"USD";
    [FIRAnalytics logEventWithName:@"ad_impression" parameters:params];
    [FIRAnalytics logEventWithName:@"Ad_Impression_Revenue" parameters:params];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] Firebase 埋点完成"];
    
    // 3. Facebook 事件上报
    NSMutableDictionary *fbParams = [NSMutableDictionary dictionary];
    fbParams[@"ad_platform"] = @"ironSource";
    fbParams[@"ad_unit"] = impressionData.mediationAdUnitId ?: @"";
    fbParams[@"ad_format"] = ad_format;
    fbParams[@"ad_source"] = impressionData.adNetwork ?: @"";
    fbParams[@"ad_unit_name"] = impressionData.instanceName ?: @"";
    fbParams[@"ad_unit_source"] = adSource;
    fbParams[@"value"] = @(revenueUSD);
    fbParams[@"currency"] = @"USD";
    
    [FBSDKAppEvents.shared logEvent:@"ad_impression" parameters:fbParams];
    [FBSDKAppEvents.shared logEvent:@"Ad_Impression_Revenue" parameters:fbParams];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] Facebook 事件上报完成"];

    // 4. 10个等级的太极打点机制
    [self reportMultiLevelTaichiRevenue:revenueUSD adFormat:ad_format adSource:adSource];

    [IMLogUtils info:IMLogTagAd format:@"🎬 [LPMImpressionData] 💸 Impression Data 处理完成"];
}

#pragma mark - 10个等级的太极打点机制


// =============== 配置：10 档（0.01 ~ 0.10，每档 +0.01） ===============
static inline NSArray<NSNumber *> *WDRevenueTiersUSD(void) {
    return @[@0.01, @0.02, @0.03, @0.04, @0.05, @0.06, @0.07, @0.08, @0.09, @0.10];
}

// 事件名与阈值一一对应，001~010 分别对应 0.01~0.10
static inline NSArray<NSString *> *WDRevenueEventNames(void) {
    return @[
        @"Total_Ads_Revenue_001", // 0.01
        @"Total_Ads_Revenue_002", // 0.02
        @"Total_Ads_Revenue_003", // 0.03
        @"Total_Ads_Revenue_004", // 0.04
        @"Total_Ads_Revenue_005", // 0.05
        @"Total_Ads_Revenue_006", // 0.06
        @"Total_Ads_Revenue_007", // 0.07
        @"Total_Ads_Revenue_008", // 0.08
        @"Total_Ads_Revenue_009", // 0.09
        @"Total_Ads_Revenue_010"  // 0.10
    ];
}

// =============== 本地持久化 Key ===============
static NSString * const kWDTotalUSDKey = @"TaichiTroasTotalUSD"; // 累计总额(USD)
static NSString * const kWDLastTierKey = @"TaichiTroasLastTier"; // 已触发最高档位 index（-1 表示未触发）

// =============== 串行队列（防并发竞态） ===============
static dispatch_queue_t WDRevenueQueue(void) {
    static dispatch_queue_t q;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        q = dispatch_queue_create("com.wd.revenue.milestones", DISPATCH_QUEUE_SERIAL);
    });
    return q;
}

#pragma mark - 10 档里程碑上报（累计总额 + 已触发最高档位）

/**
 里程碑模型：
 - 仅维护 累计总额(totalUSD) 与 已触发最高档位(lastTier)
 - 每次新增 delta 后，计算最高可达档位 currentTier
 - 若 currentTier > lastTier：从 lastTier+1 ~ currentTier 依次上报（可能补齐多个档）
 - 避免“每档独立缓存”的重复/漏报/余量丢失问题
*/
- (void)reportMultiLevelTaichiRevenue:(double)revenueUSD
                             adFormat:(NSString *)adFormat
                             adSource:(NSString *)adSource
{
    if (revenueUSD <= 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ [RevTier] delta<=0，忽略"];
        return;
    }

    dispatch_async(WDRevenueQueue(), ^{
        NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;

        // 1) 更新累计
        double total = [ud doubleForKey:kWDTotalUSDKey];
        double newTotal = total + revenueUSD;
        [ud setDouble:newTotal forKey:kWDTotalUSDKey];

        [IMLogUtils info:IMLogTagAd format:@"🧮 [RevTier] 累计更新: old=%.6f → new=%.6f (+%.6f)", total, newTotal, revenueUSD];

        // 2) 计算当前最高可达档位
        NSArray<NSNumber *> *tiers = WDRevenueTiersUSD();
        NSInteger currentTier = -1;
        for (NSInteger i = tiers.count - 1; i >= 0; i--) {
            if (newTotal >= tiers[i].doubleValue) {
                currentTier = i; break;
            }
        }

        NSInteger lastTier = -1;
        if ([ud objectForKey:kWDLastTierKey] != nil) {
            lastTier = (NSInteger)[ud integerForKey:kWDLastTierKey];
        }

        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier] lastTier=%ld | currentTier=%ld", (long)lastTier, (long)currentTier];

        // 3) 补齐新跨越的档位
        if (currentTier > lastTier) {
            NSArray<NSString *> *events = WDRevenueEventNames();
            for (NSInteger i = lastTier + 1; i <= currentTier; i++) {
                NSString *eventName = events[i];
                NSNumber *threshold = tiers[i];

                // Firebase：事件名与门槛一一对应
                NSDictionary *fa = @{
                    kFIRParameterValue: @(newTotal),         // 传累计总额（便于分析）
                    kFIRParameterCurrency: @"USD",
                    @"ad_format": adFormat ?: @"",
                    @"ad_source": adSource ?: @"",
                    @"tier_index": @(i),
                    @"tier_threshold": threshold
                };
                [FIRAnalytics logEventWithName:eventName parameters:fa];

                // Facebook：同样触发 FB_ 前缀的事件
                NSDictionary *fb = @{
                    FBSDKAppEventParameterNameCurrency: @"USD",
                    @"ad_format": adFormat ?: @"",
                    @"ad_source": adSource ?: @"",
                    @"tier_index": @(i),
                    @"tier_threshold": threshold
                };
                [[FBSDKAppEvents shared]logEvent:[@"FB_" stringByAppendingString:eventName] valueToSum:newTotal parameters:fb];
                
                

                [IMLogUtils info:IMLogTagAd format:@"🚩 [RevTier] 触发档位=%ld | event=%@ | threshold=%.2f | total=%.6f",
                      (long)i, eventName, threshold.doubleValue, newTotal];
            }

            [ud setInteger:currentTier forKey:kWDLastTierKey];
            [IMLogUtils info:IMLogTagAd format:@"📝 [RevTier] 更新 lastTier=%ld", (long)currentTier];
        } else {
            [IMLogUtils info:IMLogTagAd format:@"⏭️ [RevTier] 未跨越新档位，不触发事件"];
        }

        // 不需要 synchronize；系统会自行刷盘
    });
}

#pragma mark - 调试/维护辅助（可选）

- (void)wd_resetRevenueMilestonesForDebug {
    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
    [ud removeObjectForKey:kWDTotalUSDKey];
    [ud removeObjectForKey:kWDLastTierKey];
    [IMLogUtils info:IMLogTagAd format:@"🧹 [RevTier] 已清除累计&档位状态（仅调试）"];
}

@end
